import {getInterfaceInfoById, invokeInterfaceInfo,} from '@/services/shApi-backend/interfaceInfoController';
import {getFreeInterfaceCount} from '@/services/shApi-backend/userInterfaceInfoController';
import {useParams} from '@@/exports';
import {PageContainer} from '@ant-design/pro-components';
import {Button, Card, Descriptions, Divider, Form, Input, InputNumber, message, Modal,} from 'antd';
import React, {useEffect, useState} from 'react';
import {useModel} from "@umijs/max";
import {interfaceTOrder} from "@/services/shApi-order/orderController";

/**
 * 接口详情页面
 * @constructor
 */
const Index: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<API.InterfaceInfoVo>();
  const [invokeRes, setInvokeRes] = useState<any>();
  const [invokeLoading, setInvokeLoading] = useState(false);
  const params = useParams();
  // const [rechargeModalVisible, setRechargeModalVisible] = useState(false);
  const [orderData, setOrderData] = useState<API.InterfaceInfo>();
  const [orderModalOpen, setAddOrderModalOpen] = useState(false);
  const [orderCount, setOrderCount] = useState(1);
  const [totalAmount, setTotalAmount] = useState(1.0);
  const {initialState, setInitialState} = useModel('@@initialState');
  const {loginUser} = initialState;
  const [interfaceStatus, setInterfaceStatus] = useState<string>('');
  const loadData = async () => {
    if (!params.id) {
      message.error('参数错误不存在');
    }
    setLoading(true);
    try {
      const res = await getInterfaceInfoById({
        id: Number(params.id),
      });
      setData(res.data);
      setInterfaceStatus(res.data?.status); // 正确地更新状态
    } catch (error: any) {
      message.error('请求失败，' + error.message);
    }
    setLoading(false);
  };

  const showAddOrderModal = () => {
    setTotalAmount(parseFloat((orderCount * parseFloat(data?.charging)).toFixed(2)));
    setAddOrderModalOpen(true);
  };

  // 这里时加载数据的逻辑
  useEffect(() => {
    loadData();
  }, []);

  const onFinish = async (values: any) => {
    if (!params.id) {
      message.error('接口不存在');
      return;
    }
    console.log(interfaceStatus)
    if (interfaceStatus !== 1) {
      message.error('接口已关闭');
      return;
    }
    setInvokeLoading(true);
    try {
      const res = await invokeInterfaceInfo({
        id: params.id,
        ...values,
      });
      if (res.code === 0) {
        setInvokeRes(res.data);
        message.success('请求成功');
      }
    } catch (error: any) {
      message.error('请求失败，' + error.message);
    }
    setInvokeLoading(false);
  };

  // 点击购买确定
  const handleAddOrderOk = async () => {
    setLoading(true);
    try {
      const res = await interfaceTOrder({
        interfaceId: data?.id,
        count: orderCount,
        userId: loginUser?.id,
        totalAmount: totalAmount,
        charging: data?.charging,
        chargingId: data?.chargingId,
      });
      if (res.code === 0) {
        message.success('订单创建成功');
      }
    } catch (error: any) {
      message.error('请求失败，' + error.message);
    }
    setLoading(false);
    loadData();
    setAddOrderModalOpen(false);
  };

  // 点击购买取消
  const handleAddOrderCancel = () => {
    setAddOrderModalOpen(false);
  };

  const onChangeOrderCount = (value: number) => {
    setOrderCount(value);
    setTotalAmount(parseFloat((value * parseFloat(data?.charging)).toFixed(2)));
  };

  // 点击获取
  const getFreeInterface = async () => {
    setInvokeLoading(true);
    try {
      const res = await getFreeInterfaceCount({
        userId: loginUser?.id,
        interfaceId: data?.id,
        lockNum: 100,
      });
      if (res.data) {
        alert('获取成功')
      } else {
        alert('获取失败');
      }
    } catch (error: any) {
      alert('请求失败' + error);
    }
    setInvokeLoading(false);
    loadData();
    return
  };

  return (
    <PageContainer title={'查看接口文档'}>
      <Card loading={loading}>
        {data ? (
          <Descriptions
            title={data?.name}
            column={1}
            extra={
              data.charging ? (
                <Button onClick={showAddOrderModal}>购买</Button>
              ) : (
                <Button onClick={getFreeInterface}>获取</Button>
              )
            }
          >
            <Descriptions.Item label="接口状态">{data.status ? '正常' : '关闭'}</Descriptions.Item>
            <Descriptions.Item label="描述">{data.description}</Descriptions.Item>
            {data.charging ? (
              <>
                <Descriptions.Item label="计费">{data.charging} 元 / 条</Descriptions.Item>
                <Descriptions.Item label="接口剩余调用次数">
                  {data.availablePieces == null ? '0' : data.availablePieces}次
                </Descriptions.Item>
              </>
            ) : (
              <Descriptions.Item label="接口剩余调用次数">
                {data.availablePieces == null ? '0' : data.availablePieces}次
              </Descriptions.Item>
            )}
            <Descriptions.Item label="请求地址">{data.url}</Descriptions.Item>
            <Descriptions.Item label="请求方法">{data.method}</Descriptions.Item>
            <Descriptions.Item label="请求参数">
              {data.requestParams == null ? '无' : data.requestParams}
            </Descriptions.Item>
            <Descriptions.Item label="请求头">
              {data.requestHeader == null ? '无' : data.requestHeader}
            </Descriptions.Item>
            <Descriptions.Item label="响应头">
              {data.responseHeader == null ? '无' : data.responseHeader}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{data.createTime}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{data.updateTime}</Descriptions.Item>
          </Descriptions>
        ) : (
          <>接口不存在</>
        )}
      </Card>
      <Divider/>
      <Card title="在线测试">
        <Form name="invoke" layout="vertical" onFinish={onFinish}>
          <Form.Item label="请求参数" name="userRequestParams">
            <Input.TextArea/>
          </Form.Item>
          <Form.Item wrapperCol={{span: 16}}>
            <Button type="primary" htmlType="submit">
              调用
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Divider/>
      <Card title="返回结果" loading={invokeLoading}>
        {invokeRes}
      </Card>

      <Modal
        title="购买接口"
        open={orderModalOpen}
        onOk={handleAddOrderOk}
        onCancel={handleAddOrderCancel}
      >
        <Descriptions title={data?.name} size="small" layout="vertical" bordered>
          <Descriptions.Item label="接口状态">{data?.status ? '正常' : '关闭'}</Descriptions.Item>
          <Descriptions.Item label="计费">
            {data?.charging == null ? '0' : data.charging} 元 / 次
          </Descriptions.Item>
          <Descriptions.Item label="接口剩余调用次数">
            {data?.availablePieces == null ? '0' : data.availablePieces}次
          </Descriptions.Item>
          <Descriptions.Item label="请求方法">{data?.method}</Descriptions.Item>
          <Descriptions.Item label="请求地址">{data?.url}</Descriptions.Item>
          <Descriptions.Item label="购买次数">
            <InputNumber
              min={1}
              // max={data?.availablePieces}
              defaultValue={1}
              onChange={onChangeOrderCount}
            />
          </Descriptions.Item>
        </Descriptions>
        <Divider/>
        <b>总计：{totalAmount}元</b>
      </Modal>
    </PageContainer>
  );
};
export default Index;
